package service

import (
	"time"
	"todo_list/model"
	"todo_list/senializer"
)

//创建任务的服务
type CreateTaskService struct {
	Title   string `form:"title" json:"title" binding:"required,min=2,max=100"`
	Content string `form:"content" json:"content" binding:"max=1000"`
	Status  int    `form:"status" json:"status"` //0 待办   1已完成
}


//创建任务的服务
type UpdateTaskService struct {
	Title   string `form:"title" json:"title" binding:"required,min=2,max=100"`
	Content string `form:"content" json:"content" binding:"max=1000"`
	Status  int    `form:"status" json:"status"` //0 待办   1已完成
}

//展示任务详情的服务
type ShowTaskService struct {
}

//展示全部备忘录
type ListTasksService struct {
	PageNum  int `form:"PageNum" json:"PageNum"`
	PageSize int `form:"PageSize" json:"PageSize"`
}

//新增一条备忘录
func (service *CreateTaskService) Create(id uint) senializer.Response {
	var user model.User
	code := 200
	model.DB.First(&user, id)
	task := model.Task{
		User:      user,
		Uid:       user.ID,
		Title:     service.Title,
		Content:   service.Content,
		Status:    0,
		StartTime: time.Now().Unix(),
		EndTime:   0,
	}
	err := model.DB.Create(&task).Error
	if err != nil {
		code = 500
		return senializer.Response{
			Status: code,
			Msg:    "创建备忘录失败",
		}
	}
	return senializer.Response{
		Status: code,
		Msg:    "创建备忘录成功",
	}

}

//查询一条备忘录
func (service *ShowTaskService) Show(tid string) senializer.Response {
	var task model.Task
	code := 200
	err := model.DB.First(&task, tid).Error
	if err != nil {
		code = 500
		return senializer.Response{
			Status: code,
			Msg:    "查询失败",
		}
	}
	return senializer.Response{
		Status: code,
		Data:   senializer.BuildTask(task),
	}
}

func (service *ListTasksService) List(id uint) senializer.Response {
	var tasks []model.Task
	count := 0
	if service.PageSize == 0 {
		service.PageSize = 15
	}
	model.DB.Model(model.Task{}).Preload("User").Where("uid = ?", id).Count(&count).
		Limit(service.PageSize).Offset((service.PageNum - 1) * service.PageSize).
		Find(&tasks)
	return senializer.BuildListResponse(senializer.BuildTasks(tasks), uint(count))
}


func (service *UpdateTaskService) Update(tid string) senializer.Response {
	var task model.Task
	code := 200
	model.DB.First(&task,tid)
	task.Content = service.Content
	task.Status = service.Status
	task.Title = service.Title
	err := model.DB.Save(&task).Error
	if err != nil {
		code = 500
		return senializer.Response{
			Status: code,
			Msg: "更新失败",
		}
	}
	return senializer.Response{
		Status: code,
		Msg: "更新成功"，
	}
}
